﻿using System.Net;
using System.Text;
using Furion.DynamicApiController;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using 微信信息管理系统.Code.Model;

namespace 微信信息管理系统.Code.Service;

public class ToolService : IDynamicApiController
{
    private readonly IFreeSql _fsql;

    public ToolService(IFreeSql fsql)
    {
        _fsql = fsql;
    }

    [HttpPost, NonUnify]
    public async Task<Res<object>> UploadFileAsync( IFormFile file,int rname)
    {
        // 保存到网站根目录下的 uploads 目录
        var savePath = Path.Combine(Furion.App.HostEnvironment.ContentRootPath, "wwwroot", "uploads", DateTime.Now.ToString("yyyyMMdd"));
        if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath);

        if (file.Length > 0)
        {
            var filename = rname == 1 ? Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName) : file.FileName;
            // 避免文件名重复，采用 GUID 生成
            var filePath = Path.Combine(savePath, filename); // 可以替代为你需要存储的真实路径

            // 生成网址路径
            var urlPath = $"/uploads/{DateTime.Now.ToString("yyyyMMdd")}/{filename}";
            if (File.Exists(filePath))
            {
                //如果2个文件大小一样，则认为是同一个文件
                if (file.Length == new FileInfo(filePath).Length)
                {
                    return new Res<object>(new {value = (object) urlPath});
                }

                return new Res<object>("文件已存在", false);
            }

            using (var stream = System.IO.File.Create(filePath))
            {
                await file.CopyToAsync(stream);
            }

            return new Res<object>(new {value = (object) urlPath});
        }


        // 在动态 API 直接返回对象即可，无需 OK 和 IActionResult
        return new Res<object>(false);
    }
}